//矩阵是个数学表达
//平移,旋转,缩放---这些坐标系抽象成一个矩阵,方便运算
//对于人类比较难以直观理解,对于电脑友好

//3*3矩阵
//左乘法
//矩阵相乘满足结合律,不满足交换律
var Matrix = Class.create({
  constructor: function(m11, m12, m21, m22, tx, ty) {
    if (arguments.length) {
      this.a = m11;
      this.b = m21;
      this.c = m12;
      this.d = m22;
      this.tx = tx;
      this.ty = ty;
    } else {
      this.a = this.d = 1;
      this.b = this.c = this.tx = this.ty = 0;
      return this;
    }
  },


  //  ma  mc  mx
  //  mb  md  my
  //  0   0    1

  //  a  c    tx
  //  b  d    ty
  //  0  0    1
  //  a*ma+b*mc          a*mb+b*md                tx*ma+ty*mc+mx
  //  c*ma+d*mc          c*mb+d*md                tx*mb+ty*md+my
  //   0                    0                           1
  concat: function(mtx) {
    var args = arguments;
    var a = this.a;
    var b = this.b;
    var c = this.c;
    var d = this.d;
    var tx = this.tx;
    var ty = this.ty;
    var ma, mb, mc, md, mx, my;
    if (args.length >= 6) {
      ma = args[0];
      mb = args[1];
      mc = args[2];
      md = args[3];
      mx = args[4];
      my = args[5];
    } else {
      ma = mtx.a;
      mb = mtx.b;
      mc = mtx.c;
      md = mtx.d;
      mx = mtx.tx;
      my = mtx.ty;
    }

    this.a = a * ma + b * mc;
    this.b = a * mb + b * md;
    this.c = c * ma + d * mc;
    this.d = c * mb + d * md;
    this.tx = tx * ma + ty * mc + mx;
    this.ty = ty * mb + ty * md + my;
    return this;
  },

  //  a  c    tx
  //  b  d    ty
  //  0  0    1
  rotate: function(angle) {
    var sin = Math.sin(angle);
    var cos = Math.cos(angle);
    var a = this.a;
    var b = this.b;
    var c = this.c;
    var d = this.d;
    var tx = this.tx;
    var ty = this.ty;

    this.a = a * cos - b * sin;
    this.b = a * sin + b * cos;
    this.c = c * cos - d * sin;
    this.d = c * sin + d * cos;
    this.tx = tx * cos - ty * sin;
    this.ty = tx * sin + ty * cos;

    return this;
  },

  //  a  c    tx
  //  b  d    ty
  //  0  0    1
  scale: function(sx, sy) {
    this.a = this.a * sx;
    this.b = this.b * sy;
    this.c = this.c * sx;
    this.d = this.d * sy;
    this.tx = this.tx * sx;
    this.ty = this.ty * sy;
    return this;
  },

  translate: function(dx, dy) {
    this.tx = this.tx + dx;
    this.ty = this.ty + dy;
    return this;
  },

  //1 0 0
  //0 1 0
  //0 0 1
  //单位矩阵
  //符合规定的矩阵与单位矩阵相乘，矩阵不变
  identity: function() {
    this.a = this.d = 1;
    this.b = this.c = this.tx = this.ty = 0;
    return this;
  },

  //point:我们需要平移的点
  //round:是否对坐标的点进行向上取整
  //returnNew:是否返回一个新点
  transformPoint:function(point,round,returnNew){
      var x=point.x*this.a+point.y*this.c+this.tx;
      var y=point.x*this.b+point.y*this.d+this.ty;

      if(round){
          x=x+0.5>>0;
          y=y+0.5>>0;
      }

      if(returnNew) return{x:x,y:y}

      point.x=x;
      point.y=y;
      return point;

  }
});
